<template>
	<view :class="[primarySize()]">
		<view class="page-foot bg-white">
			<view class="ptb10 plr30 flex-box">
				<view class="btn4" @click="bindPrev()">上一步</view>
				<view class="btn5 ml30" @click="bindSave()">完成</view>
			</view>
		</view>
		<view class="container">
			<view class="p30">
				<view class="box1">
					<view class="fwb fs34 col1 lh34 pb40">
					{{job.job_category && job.job_category.category_name ? job.job_category.category_name : '职位信息'}}
				</view>
					<view class=" flex-box">
						<view class="must fs32 col1">岗位名称</view>
						<input type="text" data-name="job_name" @input="bindInput" placeholder="请输入"
							class="flex-grow-1 tr fs30 col3 pl30" maxlength="10" :value="job.job_name"
							placeholder-class="col9" />
					</view>
					<view class="mt10 fs26 col8">10个字以内</view>
					<view class="mt30 flex-box">
						<view class="must fs32 col1 flex-grow-1">招聘类型</view>
						<view class="switch ml40" :class="job.type==2?'ac':''" @click="bindJobTypeChange(2)">兼职</view>
						<view class="switch ml40" :class="job.type==1?'ac':''" @click="bindJobTypeChange(1)">全职</view>
					</view>
					<view class="mt30 flex-box">
						<view class="must fs32 col1">招聘人数</view>
						<input type="number" data-name="num" @input="bindInput" :value="job.num" placeholder="请输入"
							class="flex-grow-1 tr fs30 col3 pl30" placeholder-class="col9" />
					</view>
				</view>
				<view class="mt20 box1">
					<view class="fwb fs34 col1 lh34">选择职位薪资</view>
					<picker class="mt40" @change="bindSalaryTypeChange" range-key="name" :value="salaryPickerIndex"
						:range="salaryTypes">
						<view class="flex-box">
							<view class="fs32 col1">选择薪资范围</view>
							<view class="flex-grow-1 pl30 tr fs30"
								:class="[!getListItemById(salaryTypes,job.salary_type)?'col9':'col3']">
								{{getListItemAttrById(salaryTypes, job.salary_type, 'name', '请选择')}}
							</view>
							<image src="https://admin.mosizp.cn/static/public/arrow-r.png" mode="widthFix" class="ico12 ml10"></image>
						</view>
					</picker>
					<view class="flex-box block_item every_price mt20" v-if="job.salary_type && job.salary_type != 0">
						<input type="number" maxlength="10" :value="job.salary_min" placeholder="00000"
							@input="bindSalaryMinInput" placeholder-class="cold7" class="flex-grow-1"></input>
						<view>-</view>
						<input type="number" maxlength="10" :value="job.salary_max" placeholder="00000"
							@input="bindSalaryMaxInput" class="flex-grow-1 pl15" placeholder-class="cold7"></input>
						<view>{{unit}}</view>
					</view>
				</view>
				<view class="mt20 box1" style="padding-bottom: 0;">
					<view class="fwb fs34 col1 lh34">职位工作地点</view>
					<view class="info_item picker_item" style="border-top: none;">
						<multi-select class="" :items="areas" @change="bindDistrictChange" id_key="id" name_key="name"
							:value="job.district_id">
							<view class="flex-box">
								<view class="fs32 col1">发布区域</view>
								<view class="flex-grow-1 pl30 tr fs30" :class="[!favAreaName?'col9':'col3']">
									{{!favAreaName?'请选择':favAreaName}}
								</view>
								<image src="https://admin.mosizp.cn/static/public/arrow-r.png" mode="widthFix" class="ico12 ml10"></image>
							</view>
						</multi-select>

					</view>
					<view class="picker_item" @click="workMap">
						<view class="flex-box">
							<view class="fs32 col1">工作地点</view>
							<view class="flex-grow-1 pl30 tr fs30" :class="[true?'col8':'col3']">{{true?'+添加地点':''}}
							</view>
							<image src="https://admin.mosizp.cn/static/public/arrow-r.png" mode="widthFix" class="ico12 ml10"></image>
						</view>
					</view>
					<template v-if="locations&&locations.length>0">
						<view class="picker_item flex-box" style="padding-bottom: 20rpx;"
							v-for="(address,index) in locations">
							<view class="flex-grow-1 pl30">
								<view class="fs32 col1 lh44 m-ellipsis">{{address.address_name}}</view>
								<view class="m-ellipsis-l2 mt20 fs30 col9 lh42">{{address.address}}</view>
							</view>
						</view>
					</template>
				</view>
				<view class="box1 mt20">
					<view class="fwb fs34 col1 lh34 must">岗位人员要求</view>
					<view class="mt40 pb30">
						<multi-select :items="educationLevels" :value="job.education_level_id"
							@change="bindEducationLevelChange">
							<view class="flex-box">
								<view class="fs32 col1">学历要求</view>
								<view class="flex-grow-1 pl30 tr fs30"
									:class="[!getListItemById(educationLevels,job.education_level_id)?'col9':'col3']">
									{{getListItemAttrById(educationLevels, job.education_level_id, 'name', '请选择')}}
								</view>
								<image src="https://admin.mosizp.cn/static/public/arrow-r.png" mode="widthFix" class="ico12 ml10"></image>
							</view>
						</multi-select>
					</view>

					<view class="picker_item">
						<multi-select :items="experienceOptions" :value="job.work_experience_id"
							@change="bindWorkExperienceChange">
							<view class="flex-box">
								<view class="fs32 col1">工作年限</view>
								<view class="flex-grow-1 pl30 tr fs30"
									:class="[!getListItemById(experienceOptions,job.work_experience_id)?'col9':'col3']">
									{{getListItemAttrById(experienceOptions, job.work_experience_id, 'name', '请选择')}}
								</view>
								<image src="https://admin.mosizp.cn/static/public/arrow-r.png" mode="widthFix" class="ico12 ml10"></image>
							</view>
						</multi-select>
					</view>

					<view class="picker_item">
						<view class="flex-box">
							<view class="fs32 col1">性别要求</view>
							<view class="flex-grow-1 tr">
								<view class="switch ml20" :class="item.id==job.gender?'ac':''"
									@click="bindGenderChange(item.id)" v-for="(item,index) in genderOptions">{{item.name}}</view>
							</view>
						</view>
					</view>

					<view class="picker_item">
						<view class="flex-box">
							<view class="fs32 col1">年龄要求</view>
							<view class="flex-grow-1 tr flex-box">
								<input type="number" maxlength="3" v-model="job.age_min"
									@input="bindAgeMinInput" placeholder="最小" class="age-input tc fs30 col3" placeholder-class="col9" />
								<view class="col3 plr10">-</view>
								<input type="number" maxlength="3" v-model="job.age_max"
									@input="bindAgeMaxInput" placeholder="最大" class="age-input tc fs30 col3" placeholder-class="col9" />
								<view class="col3 pl10">岁</view>
							</view>
						</view>
					</view>

				</view>
				<view class="box1 mt20">
					<view class="fwb fs34 col1 lh34">红包招聘</view>
					<view class="mt40 pb30 flex-box">
						<view class=" fs32 col1">补贴金额</view>
						<input maxlength="10" type="digit" v-model="red_packet"
							@input="bindRedPacketInput" placeholder="填写补贴金额" class="flex-grow-1 tr fs30 col3 pl30" placeholder-class="col9" />
							<view class="col3 pl10">元</view>
					</view>
					<view class="mt30 fs32 col1">补贴说明</view>
					<textarea class="textarea" maxlength="200" v-model="red_packet_instruction"
							@input="bindRedPacketInstructionInput" placeholder="填写补贴说明"></textarea>
				</view>
				<view class="box1 mt20">
					<view class="must fwb fs34 col1 lh34">联系方式</view>
					<view class="mt40 pb30 flex-box">
						<view class=" fs32 col1">联系人</view>
						<input type="text" data-name="contact_person" @input="bindInput" :value="job.contact_person"
							placeholder="请输入联系人姓名" class="flex-grow-1 tr fs30 col3 pl30" placeholder-class="col9" />
					</view>
					<view class="ptb30 bt flex-box">
						<view class=" fs32 col1">联系电话</view>
						<input type="text" data-name="contact_phone" @input="bindInput" :value="job.contact_phone"
							placeholder="请输入联系人电话" class="flex-grow-1 tr fs30 col3 pl30" placeholder-class="col9" />
					</view>
					<view class="pt30 bt flex-box">
						<view class=" fs32 col1">联系邮箱</view>
						<input type="text" data-name="contact_email" @input="bindInput" :value="job.contact_email"
							placeholder="请输入联系人邮箱" class="flex-grow-1 tr fs30 col3 pl30" placeholder-class="col9" />
					</view>
				</view>
				<view class="box1 mt20">
					<view class="must fwb fs34 col1 lh34">选择企业福利</view>
					<view class="pt10">
						<view class="label" @click="check(index)" :class="[{active:item.checked}]"
							v-for="(item, index) in benefits">{{item.name}}</view>
					</view>
				</view>
				<view class="box1 mt20">
					<view class="must fwb fs34 col1 lh34">完善职位描述</view>
					<view class="mt30 fs32 col1">职位描述</view>
					<textarea class="textarea" data-name="responsibility" @input="bindInput" :value="job.responsibility"
						maxlength='500' placeholder-class="col9" placeholder="请填写岗位职责"></textarea>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	var validate = require("../../xilu/validate.js");
	export default {
		data() {
			return {

				job: {
					job_category: {},
					benefit_ids: [],
					benefits: [],
					salary_type: 3  // 默认按月结算
				},
				salaryTypes: [{
					id: 3,
					name: '按月结算'
				}, {
					id: 2,
					name: '按天结算'
				}, {
					id: 1,
					name: '按小时结算'
				}, {
					id: 0,
					name: '面议'
				}],
				salaryPickerIndex: 0,
				unit: '',
				areas: [],
				favAreaName: '',
				experienceOptions: [],
				educationLevels: [],
				benefits: [],
				addressList: [],
				red_packet:'',
				red_packet_instruction:'',
				locations:[],
				genderOptions: [{
					id: 0,
					name: '不限'
				}, {
					id: 1,
					name: '男'
				}, {
					id: 2,
					name: '女'
				}]
			}
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.primaryColor()
			})
		},
		onLoad: function(options) {
			// 先加载基础数据，确保组件有数据可显示
			this.$util.getAreasTree(3, false).then(items => {
				this.areas = items;
			});
			this.$util.getWorkExperienceOptions().then(items => {
				this.experienceOptions = items;
			})
			this.$util.getEducationLevels().then(levels => {
				this.educationLevels = levels;
			});
			// 加载福利列表
			this.$util.getBenefits().then(benefits => {
				this.benefits = benefits;
			});
			this.fetchAddress();

			this.getOpenerEventChannel().on('jobTransfer', job => {
				console.log('Received job data:', job);
				this.favAreaName = job.fav_area_name;

				// 处理薪资类型
				if (job.salary_type !== undefined) {
					this._formatUnit();
					let salaryPickerIndex = 0;
					for (let i = 0; i < this.salaryTypes.length; i++) {
						let item = this.salaryTypes[i];
						if (item.id == job.salary_type) {
							salaryPickerIndex = i;
							break;
						}
					}
					this.salaryPickerIndex = salaryPickerIndex;
				}

				// 处理福利标记
				job.benefit_ids = job.benefit_ids || [];
				job.benefits = job.benefits || [];

				// 标记已选中的福利
				if (job.benefit_ids.length > 0) {
					this.benefits.forEach(item => {
						if (job.benefit_ids.indexOf(item.id) > -1) {
							this.$set(item, 'checked', true);
						}
					});
				}

				// 更新job数据
				this.job = job;
			});
		},
		methods: {
			  bindJobTypeChange(type) {
				  this.$set(this.job, 'type', type);
			  },
			bindGenderChange(id) {
				this.$set(this.job, 'gender', id);
			},
			bindAgeMinInput(event) {
				this.job.age_min = parseInt(event.detail.value) || null;
			},
			bindAgeMaxInput(event) {
				this.job.age_max = parseInt(event.detail.value) || null;
			},
			_formatUnit() {
				let type = this.job.salary_type;
				if (type === 1) {
					this.unit = '元/时';
				} else if (type === 2) {
					this.unit = '元/日';
				} else if (type === 3) {
					this.unit = '元/月'
				}
			},
			bindRedPacketInput: function(event) {
				this.red_packet = parseInt(event.detail.value)
			},
			bindRedPacketInstructionInput: function(event) {
				this.red_packet_instruction = event.detail.value
			},
			bindInput(event) {
				let field = event.currentTarget.dataset.name
				this.job[field] = event.detail.value;
			},
			bindSalaryTypeChange: function(e) {
				let index = parseInt(e.detail.value),
					type = this.salaryTypes[index].id;
				this.salaryPickerIndex = index
				this.job.salary_type = type;
				if (type === 0) {
					this.job.salary_max = null;
					this.job.salary_min = null;
					this.unit = '';
				} else {
					this.unit = '';
					this._formatUnit();
				}
			},
			bindSalaryMinInput(event) {
				this.job.salary_min = event.detail.value;
			},
			bindSalaryMaxInput(event) {
				this.job.salary_max = event.detail.value;
			},
			bindDistrictChange(event) {
				this.favAreaName = event.items.map(item => item.name).join(' - ');
				let selectedProvince = event.items[0],
					selectedCity = event.items[1],
					selectedDistrict = event.items[2];
				this.job.province_id = selectedProvince.id;
				this.job.city_id = selectedCity.id;
				this.job.district_id = selectedDistrict.id;
				this.$forceUpdate();
			},
			bindEducationLevelChange(event) {
				let items = event.items;
				let selectedLevel = items[0];
				//this.selectedEducationLevel = selectedLevel; 
				this.job.education_level_id = selectedLevel.id;
				this.$forceUpdate();
			},
			bindWorkExperienceChange(event) {
				let items = event.items;
				let selectedOption = items[0];
				//this.selectedExperienceOption = selectedOption; 
				this.job.work_experience_id = selectedOption.id;
				this.$forceUpdate();
			},
			check: function(index) {
				let benefits = this.benefits,
					benefitIds = this.job.benefit_ids,
					benefit = benefits[index],
					checked = !benefit.checked;
				if (checked) {
					benefitIds.push(benefit.id);
					this.job.benefits.push(benefit);
				} else {
					let existIndex = benefitIds.indexOf(benefit.id);
					existIndex > -1 ? benefitIds.splice(existIndex, 1) : '';
					//去除job.benefits
					for (let i = 0; i < this.job.benefits.length; i++) {
						if (this.job.benefits[i].id == benefit.id) {
							this.job.benefits.splice(i, 1);
							break;
						}
					}
				}
				this.$set(this.benefits[index], 'checked', checked);
				this.$set(this.job, 'benefit_ids', benefitIds);
				this.$forceUpdate()
			},
			fetchAddress() {
				let that = this;
				this.$core.get({
					url: '/xilujob.company_address/index',
					loading: false,
					data: {},
					success: ret => {
						let locations = that.job.locations || [];
						for (let j = 0; j < locations.length; j++) {
							for (let i = 0; i < ret.data.length; i++) {
								if (locations[j].company_address_id == ret.data[i].id) {
									ret.data[i].checked = true;
								} else {
									ret.data[i].checked = false;
								}
							}
						}
						that.addressList = ret.data;
					}
				});
			},
			
			workMap() {
				uni.navigateTo({
					url: '/pages/company/my_address',
					events: {
						'chooseLocation': location => {
							location.company_address_id = location.id
							this.locations = [location]
							
						}
					}
				})
			},
			bindPrev() {
				uni.navigateBack({});
			},
			bindSave: function(event) {
			// 先检查企业信息完整度
			this.checkCompanyInfo().then(() => {
				// 完整度检查通过，继续职位发布流程
				this.submitJob();
			}).catch((error) => {
				// 完整度检查不通过，已在 checkCompanyInfo 中处理提示
				console.log('企业信息完整度检查失败:', error);
			});
		},
		// 检查企业信息完整度
		checkCompanyInfo() {
			return new Promise((resolve, reject) => {
				this.$core.post({
					url: '/xilujob.job/check_company_info',
					loading: true,
					success: (ret) => {
						console.log('企业信息完整度检查通过:', ret);
						resolve(ret);
					},
					fail: (ret) => {
						console.log('企业信息完整度检查失败:', ret);

						// 显示错误提示
						if (ret.code === 1001 && ret.data) {
							// 完整度不足80%
							uni.showModal({
								title: '提示',
								content: `企业信息完整度为${ret.data.info_complete}%，需要达到80%才能发布职位。是否前往完善企业信息？`,
								confirmText: '去完善',
								cancelText: '取消',
								success: (res) => {
									if (res.confirm) {
										// 跳转到完善企业信息页面
										uni.navigateTo({
											url: ret.data.redirect_url || '/pages/company/improve_corporate_information'
										});
									}
								}
							});
						} else {
							// 其他错误
							uni.showToast({
								title: ret.msg || '检查企业信息失败',
								icon: 'none'
							});
						}

						reject(ret);
					}
				});
			});
		},
		// 提交职位
		submitJob: function() {
				// if(!this.agree) {
				//   uni.showToast({title: '请阅读并同意《免责声明》',icon:'none'});
				//   return;
				// }
				let data = this._formatPostData();
				var rule = [{
						name: 'job_name',
						rules: ['require'],
						errorMsg: {
							require: '请填写职位名称'
						}
					},
					{
						name: 'type',
						rules: ['require','range:1,2'],
						errorMsg: {
							require: '请选择职位类型',
							range: '请选择职位类型'
						}
					},
					{
						name: 'num',
						rules: ['require', 'gt:0'],
						errorMsg: {
							require: '请填写招聘人数',
							gt: '请填写招聘人数'
						}
					},
					{
						name: 'salary_type',
						rules: ['range:0,3'],
						errorMsg: {
							require: '请选择结薪方式',
							range: '请选择结薪方式'
						}
					},
					{
						name: 'education_level_id',
						rules: ['require', 'egt:-1'],
						errorMsg: {
							require: '请选择人员学历要求',
							egt: '请选择人员学历要求'
						}
					},
					{
						name: 'work_experience_id',
						rules: ['require', 'egt:-1'],
						errorMsg: {
							require: '请选择工作年限要求',
							egt: '请选择工作年限要求'
						}
					},
					{
						name: 'contact_person',
						rules: ['require'],
						errorMsg: {
							require: '请填写联系人'
						}
					},
					{
						name: 'contact_phone',
						rules: ['require'],
						errorMsg: {
							require: '请填写联系电话'
						}
					},
					{
						name: 'contact_email',
						rules: ['require'],
						errorMsg: {
							require: '请填写正确的邮箱'
						}
					},
					{
						name: 'benefit_ids',
						rules: ['require'],
						errorMsg: {
							require: '请选择福利'
						}
					},
					{
						name: 'responsibility',
						rules: ['require'],
						errorMsg: {
							require: '请填写岗位职责'
						}
					},
				];
				if (data.salary_type != 0) {
					rule = rule.concat([{
							name: 'salary_min',
							rules: ['require', 'gt:0'],
							errorMsg: {
								require: '请填写最低薪资',
								gt: '薪资不得低于0'
							}
						},
						{
							name: 'salary_max',
							rules: ['require', 'gt:0'],
							errorMsg: {
								require: '请填写最高薪资',
								gt: '薪资不得低于0',
							}
						},
					]);
				}

				if (!validate.check(data, rule)) {
					uni.showToast({
						title: validate.getError()[0],
						icon: 'none'
					});
					return;
				}
				if (data.salary_type != 0) {
					if (data.salary_min * 100 > data.salary_max * 100) {
						uni.showToast({
							title: '最高薪资错误',
							icon: 'none'
						});
						return;
					}
				}

				if (!this.job.id) {
					this.$core.post({
						url: '/xilujob.job_manage/add',
						data: data,
						success: (ret) => {
							let job = ret.data.job;
							uni.$emit(app.globalData.Events.JobCreate, job);
							if (getCurrentPages().length < 2) {
								uni.redirectTo({
									url: '/pages/company/position_management'
								});
							} else {
								uni.navigateBack({
									delta: 2
								});
							}
						}
					});
				} else {
					this.$core.post({
						url: '/xilujob.job_manage/edit/id/' + this.job.id,
						data: data,
						success: (ret) => {
							let job = ret.data.job;
							uni.$emit(app.globalData.Events.JobUpdate, job);
							uni.navigateBack({
								delta: 2
							});
						}
					});
				}
			},
			_formatPostData: function() {
				let job = {
					"type": this.job.type,
					"job_name": this.job.job_name,
					"num": this.job.num,
					"job_category_id": this.job.job_category_id,
					"salary_type": this.job.salary_type,
					"salary_min": this.job.salary_min,
					"salary_max": this.job.salary_max,
					"responsibility": this.job.responsibility,
					"environment_images": this.job.environment_images,
					"red_packet": this.red_packet,
					"red_packet_instruction": this.red_packet_instruction,
					"benefit_ids": this.job.benefit_ids,
					"education_level_id": this.job.education_level_id,
					"work_experience_id": this.job.work_experience_id,
					"province_id": this.job.province_id,
					"city_id": this.job.city_id,
					"district_id": this.job.district_id,
					//'town_id': this.data.job.town_id,
					"contact_person": this.job.contact_person,
					"contact_phone": this.job.contact_phone,
					"contact_email": this.job.contact_email,
					"gender": this.job.gender || 0,
					"age_min": this.job.age_min || null,
					"age_max": this.job.age_max || null,
					"locations": [],
				};
				let locations = [];
				
				
					if (this.locations.length>0) {
						locations.push({
							company_address_id: this.locations[0].id,
							province_id: this.locations[0].province_id,
							city_id: this.locations[0].city_id,
							district_id: this.locations[0].district_id,
							address_name: this.locations[0].address_name,
							address: this.locations[0].address,
							house_number: this.locations[0].house_number,
							lat: this.locations[0].lat,
							lng: this.locations[0].lng,
						})
					}
				job.locations = locations;
				return job;

			},
		}
	}
</script>

<style lang="scss" scoped>
	.box1 {
		width: 690rpx;
		background: #FFFFFF;
		border-radius: 18rpx;
		padding: 40rpx 30rpx 30rpx;

	}

	.must {
		&:before {
			content: '*';
			color: #F5584F;
			font-size: 32rpx;
			display: inline-block;
		}
	}

	.picker_item {
		border-top: 1px solid #EEEEEE;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
	}

	.pl70 {
		padding-left: 70rpx;
	}

	.bt {
		border-top: 1px solid #EEEEEE;
	}

	.label {
		margin-top: 20rpx;
		margin-right: 20rpx;
		height: 75rpx;
		border-radius: 10rpx;
		border: 1px solid #666666;
		line-height: calc(75rpx - 2px);
		text-align: center;
		padding: 0 20rpx;
		font-size: 30rpx;
		color: #333333;
		display: inline-block;
		vertical-align: top;

		&.active {
			border: 1px solid var(--primary);
			color: var(--primary);
		}
	}

	.textarea {
		width: 630rpx;
		height: 350rpx;
		background: #F9F9F9;
		border-radius: 20rpx;
		margin-top: 20rpx;
		padding: 30rpx;
		color: #333;
		font-size: 30rpx;
	}
	.switch {
		width: 122rpx;
		height: 53rpx;
		line-height: 53rpx;
		text-align: center;
		font-size: 30rpx;
		color: #666666;
		background: #EFF0F2;
		border-radius: 27rpx;

		&.ac {
			background: var(--primary);
			color: #FFFFFF;
		}
	}

	.age-input {
		width: 120rpx;
		height: 60rpx;
		background: #F9F9F9;
		border-radius: 10rpx;
		padding: 0 10rpx;
	}
</style>